package com.quectel.cms.controller.forum;


import cn.hutool.core.lang.func.LambdaUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.core.forum.ForumConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.forum.dto.mongo.ForumAuditRecordDto;
import com.quectel.core.module.forum.dto.mongo.ForumCommentDto;
import com.quectel.core.module.forum.dto.mongo.ForumPostDto;
import com.quectel.core.module.forum.service.mongo.ForumAuditRecordService;
import com.quectel.core.module.forum.service.mongo.ForumCommentService;
import com.quectel.core.module.forum.service.mongo.ForumPostService;
import com.quectel.core.module.mobileuser.dto.MobileUserDto;
import com.quectel.core.module.mobileuser.service.MobileUserService;
import com.quectel.sys.module.sys.dto.SysUserDto;
import com.quectel.sys.module.sys.service.SysUserService;
import com.quectel.util.common.*;
import com.quectel.util.kit.PageFetchKit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/05/10 11:21
 */
@RestController
@RequestMapping("forumAuditRecord")
@Tag(name = "forumAuditRecordController", description = "邻友圈审核记录相关api")
public class ForumAuditRecordController extends BaseController {

    @DubboReference
    private ForumAuditRecordService forumAuditRecordService;
    @DubboReference
    private MobileUserService mobileUserService;
    @DubboReference
    private SysUserService sysUserService;
    @DubboReference
    private ForumCommentService forumCommentService;
    @DubboReference
    private ForumPostService forumPostService;


    /**
     * 导出记录 carAccessRecord:exportExcel
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "forumAuditRecord:exportExcel")
    @Operation(summary = "导出审核记录")
    @Log(express = "导出车辆出入记录")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        List<ForumAuditRecordDto> result = PageFetchKit.fetchAll(r -> forumAuditRecordService.queryList(r), request.getParams());

        String[] headers = new String[]{"账号名称", "账号昵称", "账号手机", "审核结果", "备注", "发布内容", "发布图片", "审核人员", "审核时间"};
        List<String[]> dataList = new ArrayList<>();
        for (ForumAuditRecordDto data : result) {
            String[] item = new String[headers.length];
            item[0] = data.getMobileUserName();
            item[1] = data.getNickName();
            item[2] = data.getMobileUserMobile();
            item[3] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.LICENSE_COLOR, data.getResult() + "");
            item[4] = data.getRemark();

            String content = "";
            String imgUrls = "";
            if (ForumConstants.ForumAuditObjectEnum.POST.getType().equals(data.getSourceType())) {
                ForumPostDto forumPostDto = (ForumPostDto) data.getSourceObj();
                content = forumPostDto.getContent();
                imgUrls = JacksonUtils.toJsonString(forumPostDto.getImageUrls());

            } else if (ForumConstants.ForumAuditObjectEnum.COMMENT.getType().equals(data.getSourceType())) {
                ForumCommentDto forumCommentDto = (ForumCommentDto) data.getSourceObj();
                content = forumCommentDto.getContent();
            }

            item[5] = content;
            item[6] = imgUrls;
            SysUserDto sysUserDto = sysUserService.selectCacheById(data.getAuditUserId());
            item[7] = sysUserDto!=null?sysUserDto.getUsername():"";
            item[8] = DateUtils.format(data.getAuditTime(), DateUtils.FormatType.COMMON);
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "审核记录", headers, dataList, "审核记录");

    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "forumAuditRecord:list")
    @Operation(summary = "分页获取发帖管理列表")
    public Response<Page<ForumAuditRecordDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "手机号") @RequestParam(required = false) String mobile,
            @Parameter(description = "审核开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "审核结束时间") @RequestParam(required = false) String endTime

    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        if (StringUtils.isNotBlank(mobile)) {
            MobileUserDto mobileUserDto = mobileUserService.selectByMobile(mobile);
            if (mobileUserDto == null) {
                return Response.<Page<ForumAuditRecordDto>>ok().wrap(Page.empty(request.getPageNo(), request.getPageSize()));
            } else {
                request.put(LambdaUtil.getFieldName(ForumAuditRecordDto::getMobileUserId), mobileUserDto.getId());
            }
        }

        if (StringUtils.isNotBlank(startTime)) {
            request.put(ForumConstants.AUDIT_TIME_SLOT_KEY_PAIR.getLeft(), startTime);
        }

        if (StringUtils.isNotBlank(endTime)) {
            request.put(ForumConstants.AUDIT_TIME_SLOT_KEY_PAIR.getRight(), endTime);
        }


        int total = forumAuditRecordService.queryTotal(request.getParams());

        List<ForumAuditRecordDto> list = null;
        if (total > 0) {
            list = forumAuditRecordService.queryList(request.getParams());

            list.forEach(auditRecordDto -> {
                SysUserDto sysUserDto = sysUserService.selectCacheById(auditRecordDto.getAuditUserId());
                if(sysUserDto!=null){
                    auditRecordDto.setAuditUserName(sysUserDto.getUsername());
                }
            });

        } else {
            list = new ArrayList<>();
        }

        Page<ForumAuditRecordDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<ForumAuditRecordDto>>ok().wrap(page);
    }


    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "forumAuditRecord:info")
    @Operation(summary = "根据id查询发帖管理的详情")
    public Response<ForumAuditRecordDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (forumAuditRecordService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ForumAuditRecordDto forumAuditRecordDto = forumAuditRecordService.selectById(id);

        MobileUserDto mobileUserDto = mobileUserService.selectCacheById(forumAuditRecordDto.getMobileUserId());
        if(mobileUserDto!=null){
            forumAuditRecordDto.setNickName(mobileUserDto.getNickname());
            forumAuditRecordDto.setMobileUserName(DesensitizedUtil.chineseName(mobileUserDto.getName()));
            forumAuditRecordDto.setMobileUserMobile(DesensitizedUtil.mobilePhone(mobileUserDto.getMobile()));
        }

        if(ForumConstants.ForumAuditObjectEnum.POST.getType().equals(forumAuditRecordDto.getSourceType())){
            ForumPostDto forumPostDto = forumPostService.selectCacheById(forumAuditRecordDto.getSourceId());
            forumAuditRecordDto.setSourceObj(forumPostDto);
        }

        if(ForumConstants.ForumAuditObjectEnum.COMMENT.getType().equals(forumAuditRecordDto.getSourceType())){
            ForumCommentDto forumCommentDto = forumCommentService.selectById(forumAuditRecordDto.getSourceId());
            forumAuditRecordDto.setSourceObj(forumCommentDto);
        }

        SysUserDto sysUserDto = sysUserService.selectCacheById(forumAuditRecordDto.getAuditUserId());
        if(sysUserDto!=null){
            forumAuditRecordDto.setAuditUserName(sysUserDto.getUsername());
        }

        return Response.<ForumAuditRecordDto>ok().wrap(forumAuditRecordDto);
    }


}
